//
//  RankingListDetailViewController.m
//  安好
//
//  Created by qinlongqing on 14-9-9.
//  Copyright (c) 2014年 冯凯. All rights reserved.
//

#import "RankingListDetailViewController.h"
#import "Reachability.h"
#import "CLDataBaseController.h"
#import "RankingListDetailTableViewCell.h"
#import "MJRefresh.h"

@interface RankingListDetailViewController ()<UIAlertViewDelegate,UITableViewDelegate,UITableViewDataSource>
{
    UIImage *_imageV;
    
    UIButton *leftBTN;//本地榜
    UIButton *rightBTN;//全球榜
    
    UITableView *benDiTableView;
    UITableView *quanQiuTableView;
    
//    UILabel *userSelfScoreLabel;
    
    BOOL isLogin;
    NSString *userID;
    
    NSMutableArray *benDiBangArray;
    NSMutableArray *quanQiuBangArray;
    
    TestType currentTestType;
    
    UILabel *_hintLabel;
    
    NSInteger page;
    NSInteger pageSize;
}
@end

@implementation RankingListDetailViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    page = 1;
    pageSize = 10;
    
    self.navigationItem.title = [self getTitle];
    
    self.view.backgroundColor = UIColorFromRGB(0xe7f1f4);

    [self makeNavBar];
    
#pragma 获取存储到本地、相应项的测试数据
    switch (self.currentRow) {
        case 0:{
            currentTestType = shiLiTest;
            benDiBangArray = [[[CLDataBaseController instance] selectAllWithTestType:shiLiTest] mutableCopy];//视力
            [self sortShiLiForAllTestResult];
        }
            break;
        case 1:{
            currentTestType = xinLvTest;
            benDiBangArray = [[[CLDataBaseController instance] selectAllWithTestType:xinLvTest] mutableCopy];//色觉
            [self sortXinLvForAllTestResult];
        }
            break;

        default:
            break;
    }
#pragma navigationBar上的分享按钮
    UIButton *shareBTN = [[UIButton alloc]init];
    shareBTN.frame = CGRectMake(284, 34, 18, 18);
//    if (IPHONE5_OR_LATER) {
//        shareBTN.frame = CGRectMake(284, 34, 18, 18);
//    }
//    else{
//        shareBTN.frame = CGRectMake(284, 34, 18, 18);
//    }
    [shareBTN setImage:[UIImage imageNamed:@"share2"] forState:UIControlStateNormal];
    [shareBTN addTarget:self action:@selector(doShareBTN) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *barButton = [[UIBarButtonItem alloc]initWithCustomView:shareBTN];
    self.navigationItem.rightBarButtonItem = barButton;
#pragma 本地榜和全球榜两个按钮
    if ([[NSString stringWithFormat:@"%@",[[UserManager shareInstance] getUserIsLogin]] length] == 0) {
        isLogin = NO;
    }
    else{
        isLogin = YES;
        userID = [[UserManager shareInstance] getUserInfo].username;
    }
#pragma 本地榜按钮
    leftBTN = [[UIButton alloc]init];
    if (isLogin) {
        leftBTN.frame = CGRectMake((kScreenWidth - 290)/3, 16, 145, 40);
    }
    else{
        leftBTN.frame = CGRectMake((kScreenWidth - 290)/2, 16, 290, 40);
    }
//    if (IPHONE5_OR_LATER) {
//        if (isLogin) {//登录
//            leftBTN.frame = CGRectMake(15, 16, 145, 40);
//        }
//        else{//未登录
//            leftBTN.frame = CGRectMake(15, 16, 290, 40);
//        }
//    }
//    else{
//        if (isLogin) {//登录
//            leftBTN.frame = CGRectMake(15, 16, 145, 40);
//        }
//        else{//未登录
//            leftBTN.frame = CGRectMake(15, 16, 290, 40);
//        }
//    }
    [leftBTN setBackgroundImage:[UIImage imageNamed:@"pai_hang_bang_select"] forState:UIControlStateSelected];
    [leftBTN setBackgroundImage:[UIImage imageNamed:@"pai_hang_bang_deSelect"] forState:UIControlStateNormal];

    [leftBTN setTitle:@"本地榜" forState:UIControlStateNormal];
    [leftBTN setTitleColor:UIColorFromRGB(0x4fc1e9) forState:UIControlStateNormal];
    [leftBTN setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
    
    [leftBTN addTarget:self action:@selector(doLeftBTN) forControlEvents:UIControlEventTouchUpInside];
    
    leftBTN.selected = YES;
    leftBTN.userInteractionEnabled = NO;

    [self.view addSubview:leftBTN];
#pragma 全球榜按钮
    if (isLogin) {
        rightBTN = [[UIButton alloc]init];
        rightBTN.frame = CGRectMake(leftBTN.frame.origin.x + leftBTN.frame.size.width + (kScreenWidth - 290)/3, 16, 145, 40);
//        if (IPHONE5_OR_LATER) {
//            rightBTN.frame = CGRectMake(160, 16, 145, 40);
//        }
//        else{
//            rightBTN.frame = CGRectMake(160, 16, 145, 40);
//        }
        [rightBTN setBackgroundImage:[UIImage imageNamed:@"pai_hang_bang_select"] forState:UIControlStateSelected];
        [rightBTN setBackgroundImage:[UIImage imageNamed:@"pai_hang_bang_deSelect"] forState:UIControlStateNormal];
        
        [rightBTN setTitle:@"全球榜" forState:UIControlStateNormal];
        [rightBTN setTitleColor:UIColorFromRGB(0x4fc1e9) forState:UIControlStateNormal];
        [rightBTN setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
        
        [rightBTN addTarget:self action:@selector(doRightBTN) forControlEvents:UIControlEventTouchUpInside];
        
        [self.view addSubview:rightBTN];
    }
#pragma 本地榜所对应的tableView
    benDiTableView = [[UITableView alloc]init];
    benDiTableView.frame = CGRectMake(0, 64, kScreenWidth, kScreenHeight - 64 - 64);
//    if (IPHONE5_OR_LATER) {
//        benDiTableView.frame = CGRectMake(0, 64, 320, 440);
//    }
//    else{
//        benDiTableView.frame = CGRectMake(0, 64, 320, 352);
//    }
    benDiTableView.delegate = self;
    benDiTableView.dataSource = self;
    benDiTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    benDiTableView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:benDiTableView];
#pragma 如果登录了，则显示全球榜
    if (isLogin) {
        quanQiuBangArray = [[NSMutableArray alloc]init];

        
//        userSelfScoreLabel = [[UILabel alloc]init];
//        if (iPhone5) {
//            if (IOS7) {
//                userSelfScoreLabel.frame = CGRectMake(15, 125, 290, 20);
//            }
//            else{
//                userSelfScoreLabel.frame = CGRectMake(15, 105, 290, 20);
//            }
//        }
//        else{
//            if (IOS7) {
//                userSelfScoreLabel.frame = CGRectMake(15, 125, 290, 20);
//            }
//            else{
//                userSelfScoreLabel.frame = CGRectMake(15, 105, 290, 20);
//            }
//        }
//        userSelfScoreLabel.backgroundColor = [UIColor clearColor];
//        userSelfScoreLabel.textAlignment = NSTextAlignmentRight;
//        userSelfScoreLabel.font = [UIFont systemFontOfSize:15];
//        userSelfScoreLabel.textColor = [UIColor grayColor];
//        userSelfScoreLabel.hidden = YES;
//        userSelfScoreLabel.text = @"";
//        [self.view addSubview:userSelfScoreLabel];
        
        quanQiuTableView = [[UITableView alloc]init];
        quanQiuTableView.frame = CGRectMake(0, 64, kScreenWidth, kScreenHeight - 64 - 64);
//        if (IPHONE5_OR_LATER) {
//            quanQiuTableView.frame = CGRectMake(0, 64, 320, 440);
//        }
//        else{
//            quanQiuTableView.frame = CGRectMake(0, 64, 320, 352);
//        }
        quanQiuTableView.delegate = self;
        quanQiuTableView.dataSource = self;
        quanQiuTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        quanQiuTableView.backgroundColor = [UIColor clearColor];
        quanQiuTableView.hidden = YES;
        [quanQiuTableView addFooterWithTarget:self action:@selector(doGetQuanQiuPaiHang)];
        [self.view addSubview:quanQiuTableView];
    }
    
    _hintLabel = [[UILabel alloc] init];
    [quanQiuTableView.superview addSubview:_hintLabel];
    _hintLabel.text = @"没有更多了";
    _hintLabel.textAlignment=NSTextAlignmentCenter;
    _hintLabel.font = [UIFont systemFontOfSize:10];
    _hintLabel.textColor = [UIColor whiteColor];
    _hintLabel.backgroundColor = [UIColor blackColor];
    _hintLabel.layer.cornerRadius = 5;
    _hintLabel.layer.masksToBounds = YES;
    _hintLabel.alpha = 0;
    _hintLabel.frame = CGRectMake((quanQiuTableView.frame.size.width - 60) / 2, quanQiuTableView.frame.size.height + quanQiuTableView.frame.origin.y - 40, 60, 30);
}

- (void)makeNavBar{
    UIBarButtonItem *backBtnImg = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"公用_返回.png"] style:UIBarButtonItemStylePlain target:self action:@selector(doBack)];
    [backBtnImg setTintColor:[UIColor whiteColor]];
    self.navigationItem.leftBarButtonItem = backBtnImg;
}

-(void)doBack{
    [self.navigationController popViewControllerAnimated:YES];
}

- (NSString *)getTitle{
    NSString *title = nil;
    switch (self.currentRow) {
        case 0:
            title = @"视力";
            break;
        case 1:
            title = @"心率";
            break;

        default:
            break;
    }
    return title;
}

- (void)doShareBTN{
    CGRect rect = CGRectMake(0, 0, kScreenWidth, kScreenHeight - 64);
//    if (IPHONE5_OR_LATER) {
//        rect = CGRectMake(0, 0, 320, 504);
//    }
//    else{
//        rect = CGRectMake(0, 0, 320, 416);
//    }
    
    [self imageFromView:self.view atFrame:rect];
    
    //分享
    [self showShareView];
}

- (void)imageFromView:(UIView *)theView atFrame:(CGRect)r
{
    UIGraphicsBeginImageContext(theView.frame.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    [theView.layer renderInContext:context];
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    CGImageRef imageRef = theImage.CGImage;
    CGImageRef subImageRef = CGImageCreateWithImageInRect(imageRef, r);//原图中抠出来部分图
    UIImage *subImage = [UIImage imageWithCGImage:subImageRef];//新图
    _imageV = subImage;
//    UIGraphicsBeginImageContext(theView.frame.size);
//    CGContextRef context = UIGraphicsGetCurrentContext();
//    CGContextSaveGState(context);
//    UIRectClip(r);
//    [theView.layer renderInContext:context];
//    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
//    UIGraphicsEndImageContext();
//    
//    _imageV = theImage;
}
#pragma 实现share方法，通过点击的视图的tag值判断是什么类型的分享
- (void)share:(UITapGestureRecognizer *)shareTap{
    switch (shareTap.view.tag) {
        case 11:{//微信
            [self weixinShare:kWeiXinShareUrl :kWeiXinShareTitle :kWeiXinShareText :_imageV];
        }
            break;
        case 12:{//朋友圈
            [self weixinFriendShare:kWeiXinFriendShareUrl :kWeiXinFriendShareTitle :kWeiXinFriendShareText :_imageV];
        }
            break;
        case 13:{//短信
            [self showSMSPicker:kWeiXinFriendShareUrl :kWeiXinFriendShareTitle :kWeiXinFriendShareText :nil];
        }
            break;
        case 14:{//QQ
            [self qqShare:kQQshareUrl :kQQshareTitle :kQQshreDescription :_imageV];
        }
            break;
        case 15:{//QQ空间
            [self qqZoneShare:kQQZoneShareUrl :kQQZoneShareTitle :kQQZoneShareDescription :_imageV];
        }
            break;
        case 16:{//新浪微博
            [self sinaWeiboShare:kSinaWeiboShareUrl :kSinaWeiboShareTitle :kSinaWeiboShareText :_imageV];
        }
            break;
            
        default:
            break;
    }
}


- (void)doLeftBTN{
    if (leftBTN.selected == NO) {
        leftBTN.selected = YES;
        leftBTN.userInteractionEnabled = NO;
        benDiTableView.hidden = NO;
        if (isLogin) {
//            userSelfScoreLabel.hidden = YES;
            
            rightBTN.selected = NO;
            rightBTN.userInteractionEnabled = YES;
            
            quanQiuTableView.hidden = YES;
        }
    }
}

- (void)doRightBTN{
    if (rightBTN.selected == NO) {
        //1.有网  2.没网
        if ([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] == NotReachable) {//没网
            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"当前网络不可用,请设置后重试!" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alertView show];
        }
        else{//有网
            leftBTN.selected = NO;
            leftBTN.userInteractionEnabled = YES;
            
            benDiTableView.hidden = YES;
            
//            userSelfScoreLabel.hidden = NO;
            
            rightBTN.selected = YES;
            rightBTN.userInteractionEnabled = NO;
            
            quanQiuTableView.hidden = NO;
            
            if (quanQiuBangArray.count <= 0) {
                page = 1;
            }
            [self doGetQuanQiuPaiHang];
        }
    }
}

- (void)alertViewCancel:(UIAlertView *)alertView{
    leftBTN.selected = YES;
    benDiTableView.hidden = NO;
    
//    userSelfScoreLabel.hidden = YES;
    
    rightBTN.selected = NO;
    quanQiuTableView.hidden = YES;
}

- (void)doGetQuanQiuPaiHang{
    
    if (currentTestType == shiLiTest) {
        if (page == 1) {
            [self showActionView];
        }
        NSDictionary *parameters = @{@"platform": kPlatform,@"version":kVersion,@"page":[NSString stringWithFormat:@"%ld",page],@"pagesize":[NSString stringWithFormat:@"%ld",pageSize]};
        [[AFHTTPRequestOperationManager manager] POST:[NSString stringWithFormat:@"%@%@",kBaseURL,kGetQuanQiuBangURL] parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
            [quanQiuTableView footerEndRefreshing];

            if (page == 1) {
                [self hiddenActionView];
            }
            NSNumber * statusNum = [responseObject objectForKey:@"status"];
            NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
            NSString * statusString = [numberFormatter stringFromNumber:statusNum];
            if ([statusString isEqualToString:@"0"]) {
                alertContent([responseObject objectForKey:@"msg"]);
            }else{
                NSInteger numbers = quanQiuBangArray.count;//原来的数据
                
                if ([[responseObject objectForKey:@"data"] count] != 0) {
                    page += 1;
                    [quanQiuBangArray addObjectsFromArray:[responseObject objectForKey:@"data"]];
                }
                if (numbers == quanQiuBangArray.count) {
                    [UIView animateWithDuration:0.4f animations:^{
                        _hintLabel.alpha = 0.6;
                    } completion:^(BOOL finished) {
                        if (finished) {
                            [UIView animateWithDuration:0.5 animations:^{
                                _hintLabel.alpha = 0;
                            }];
                        }
                    }];
                }
                
                [quanQiuTableView reloadData];
            }
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            [quanQiuTableView footerEndRefreshing];

            if (page == 1) {
                [self hiddenActionView];
            }
            //提示信息用的view
            MBProgressHUD *hub = [[MBProgressHUD alloc] initWithView:self.view];
            hub.customView = [[UIView alloc]initWithFrame:CGRectZero];
            [self.view addSubview:hub];
            hub.mode = MBProgressHUDModeCustomView;
            hub.labelText = @"网络请求失败!";
            [hub show:YES];
            [hub hide:YES afterDelay:1];
        }];
    }
    else if (currentTestType == xinLvTest){
        
    }
}


- (void)sortShiLiForAllTestResult{
//    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:testUserWithDate,@"testUserName",[resultSet stringForColumn:@"Left"],@"leftResult",[resultSet stringForColumn:@"Right"],@"rightResult", nil];
//    NSString *testUserWithDate = [resultSet stringForColumn:@"Name"];

//    testUserWithDate = [testUserWithDate substringToIndex:testUserWithDate.length - 12];
    if (benDiBangArray.count > 0) {
        for (int i=0; i<benDiBangArray.count - 1; i++) {
            for (int j=0; j<benDiBangArray.count - 1 - i; j++) {
                NSDictionary *firstDict = [benDiBangArray objectAtIndex:j];
                NSDictionary *secondDict = [benDiBangArray objectAtIndex:(j + 1)];
                NSInteger firstScore = [AppConfig getShiLiTestScoreWithWordSize:[[firstDict objectForKey:@"leftResult"] integerValue]] + [AppConfig getShiLiTestScoreWithWordSize:[[firstDict objectForKey:@"rightResult"] integerValue]];
                NSInteger secondScore = [AppConfig getShiLiTestScoreWithWordSize:[[secondDict objectForKey:@"leftResult"] integerValue]] + [AppConfig getShiLiTestScoreWithWordSize:[[secondDict objectForKey:@"rightResult"] integerValue]];
                if (firstScore < secondScore) {
                    [benDiBangArray exchangeObjectAtIndex:j withObjectAtIndex:(j+1)];
                }
                else if (firstScore == secondScore){
                    NSString *firstTestUserName = [firstDict objectForKey:@"testUserName"];
                    NSInteger firstDate = [[firstTestUserName substringFromIndex:(firstTestUserName.length - 12)] integerValue];
                    NSString *secondTestUserName = [secondDict objectForKey:@"testUserName"];
                    NSInteger secondDate = [[secondTestUserName substringFromIndex:(secondTestUserName.length - 12)] integerValue];
                    if (firstDate > secondDate) {
                        [benDiBangArray exchangeObjectAtIndex:j withObjectAtIndex:(j + 1)];
                    }
                }
            }
        }
    }
//    for (int k=0; k<benDiBangArray.count; k++) {
//        NSDictionary *currentDict = [benDiBangArray objectAtIndex:k];
//        NSInteger currentScore = [self getShiLiTestScoreWithWordSize:[[currentDict objectForKey:@"leftResult"] integerValue]] + [self getShiLiTestScoreWithWordSize:[[currentDict objectForKey:@"rightResult"] integerValue]];
//        NSString *currentTestUserName = [currentDict objectForKey:@"testUserName"];
//        NSString *currentDate = [currentTestUserName substringFromIndex:(currentTestUserName.length - 12)];
//        NSLog(@"~~~~~~score=%d  name`s date=%@",currentScore,currentDate);
//    }
}

- (void)sortXinLvForAllTestResult{
    if (benDiBangArray.count > 0) {
        for (int i=0; i<benDiBangArray.count - 1; i++) {
            for (int j=0; j<benDiBangArray.count - 1 - i; j++) {
                NSDictionary *firstDict = [benDiBangArray objectAtIndex:j];
                NSDictionary *secondDict = [benDiBangArray objectAtIndex:(j + 1)];
                NSInteger firstScore = [[firstDict valueForKey:kXinLvTestResult] integerValue];
                NSInteger secondScore = [[secondDict valueForKey:kXinLvTestResult] integerValue];
                if (firstScore < secondScore) {
                    [benDiBangArray exchangeObjectAtIndex:j withObjectAtIndex:(j+1)];
                }
                else if (firstScore == secondScore){
                    NSString *firstTestUserName = [firstDict objectForKey:@"testUserName"];
                    NSInteger firstDate = [[firstTestUserName substringFromIndex:(firstTestUserName.length - 12)] integerValue];
                    NSString *secondTestUserName = [secondDict objectForKey:@"testUserName"];
                    NSInteger secondDate = [[secondTestUserName substringFromIndex:(secondTestUserName.length - 12)] integerValue];
                    if (firstDate > secondDate) {
                        [benDiBangArray exchangeObjectAtIndex:j withObjectAtIndex:(j + 1)];
                    }
                }
            }
        }
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if ([tableView isEqual:benDiTableView]) {
        return benDiBangArray.count;
    }
    else{
        return quanQiuBangArray.count;
    }
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 40;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellIdentifier = @"cell";
    RankingListDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell) {
        cell = [[RankingListDetailTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    cell.indexPath = indexPath;
    if ([tableView isEqual:benDiTableView]) {
        cell.dataEntity = [benDiBangArray objectAtIndex:indexPath.row];
        cell.isBenDiBang = YES;
    }
    else{
        cell.dataEntity = [quanQiuBangArray objectAtIndex:indexPath.row];
        cell.isBenDiBang = NO;
    }
    cell.currentTestType = currentTestType;
    [cell setup];
    [cell updata];
    return cell;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return NO;
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
